package com.xnyzc.lhy.order.feign.fallback.didi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xnyzc.lhy.common.component.config.security.TokenUser;
import com.xnyzc.lhy.common.component.didi.DiDiUrlConstant;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.component.sms.AliCloudSMSUtils;
import com.xnyzc.lhy.common.constant.*;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.entity.Rv;
import com.xnyzc.lhy.common.entity.netty.NettyDriverOrderInfo;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.EDispatchType;
import com.xnyzc.lhy.common.penum.EErrorCode;
import com.xnyzc.lhy.common.penum.gould.EGould;
import com.xnyzc.lhy.common.penum.order.EDiDiOrderStatus;
import com.xnyzc.lhy.common.penum.push.EJPushConfigKey;
import com.xnyzc.lhy.common.penum.push.EPushCode;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.IDUtil;
import com.xnyzc.lhy.common.util.RequestMethodUtil;
import com.xnyzc.lhy.common.util.TokenUtil;
import com.xnyzc.lhy.common.util.sign.AttestationTool;
import com.xnyzc.lhy.order.entity.gps.OaDVehicleGps;
import com.xnyzc.lhy.order.entity.gps.OaSysTrajectory;
import com.xnyzc.lhy.order.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.order.entity.order.OaDOrder;
import com.xnyzc.lhy.order.entity.param.order.OrderDetailParam;
import com.xnyzc.lhy.order.entity.param.synchronization.DriverSingleSynchronousParam;
import com.xnyzc.lhy.order.entity.param.synchronization.LocationSyncParam;
import com.xnyzc.lhy.order.entity.param.synchronization.RealtimeFeeSyncParam;
import com.xnyzc.lhy.order.entity.param.synchronization.StatusCallbackParam;
import com.xnyzc.lhy.common.entity.netty.StriveCallbackParam;
import com.xnyzc.lhy.order.entity.result.order.OrderDetailResults;
import com.xnyzc.lhy.order.entity.system.OaSysDispatchLog;
import com.xnyzc.lhy.order.entity.system.OaSysUser;
import com.xnyzc.lhy.order.entity.task.CloseOrderParam;
import com.xnyzc.lhy.order.entity.task.pay.PayInfo;
import com.xnyzc.lhy.order.entity.user.OaDUser;
import com.xnyzc.lhy.order.feign.amap.IAmapService;
import com.xnyzc.lhy.order.feign.didi.IDidiService;
import com.xnyzc.lhy.order.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.order.mapper.system.OaSysUserMapper;
import com.xnyzc.lhy.order.mapper.user.OaDUserMapper;
import com.xnyzc.lhy.order.mo.OrderLogMo;
import com.xnyzc.lhy.order.mq.MQProducer;
import com.xnyzc.lhy.order.service.order.IOaDOrderService;
import com.xnyzc.lhy.resource.entity.jpush.PushInfoEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Function;

import static com.xnyzc.lhy.common.constant.MqConstant.LOG_OPERATE_ORDER;

@Slf4j
@Service
public class DidiServiceFallback implements IDidiService {

    @Autowired
    private MQProducer producer;

    @Autowired
    IAmapService iAmapService;

    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    @Autowired
    RedisCommon redisCommon;

    @Autowired
    private IOaDOrderService oaDOrderService;

    @Autowired
    private OaDUserMapper oaDUserMapper;

    @Autowired
    private ThreadPoolExecutor threadPoolExecutor;

    @Autowired
    private OaSysUserMapper userMapper;




    /**
     * 司机位置同步
     *
     * @param locationSyncParam 司机同步对象
     */
    @Override
    public DiDiRv locationSync(LocationSyncParam locationSyncParam) {
        log.info("ORDER_HISTORY 订单号:[{}],滴滴推送:同步滴滴实时计价,推送失败,参数:[{}]", locationSyncParam.getOrder_id(), locationSyncParam);
        log.error("(ORDER服务)同步滴滴司机位置、推送失败，参数：{}", locationSyncParam.toString());
        return DiDiRv.wrapError(EDiDiErrorCode.networkTimeout);
    }

    @Override
    public DiDiRv getRealtimeFeeSync(RealtimeFeeSyncParam realtimeFeeSyncParam) {
        log.info("ORDER_HISTORY 订单号:[{}],滴滴推送:同步滴滴实时计价,推送失败,参数:[{}]", realtimeFeeSyncParam.getOrder_id(), realtimeFeeSyncParam);
        log.error("(ORDER服务)滴滴推送：同步滴滴实时计价、推送失败，参数：{}", realtimeFeeSyncParam.toString());
        return DiDiRv.wrapError(EDiDiErrorCode.networkTimeout);
    }

    @Override
    public Rv statusCallback(StatusCallbackParam statusCallbackParam) {
        log.info("ORDER_HISTORY 订单号:[{}],滴滴推送:同步滴滴司机状态,推送失败,参数:[{}]", statusCallbackParam.getOrder_id(), statusCallbackParam);
        log.error("(ORDER服务)滴滴推送：同步滴滴司机状态、推送失败，参数：{}", statusCallbackParam.toString());
        return Rv.error(EErrorCode.networkTimeout);
    }

    /**
     * 司机抢单
     *
     * @param param 司机抢单
     * @return
     */
    @Override
    public DiDiRv getStriveCallback(StriveCallbackParam param) {

        if (CheckUtil.objIsEmpty(param.getDriver_lat(), param.getDriver_lng())) {
            log.info("调用司机抢单接口参数问题1");
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }

        if (CheckUtil.strIsEmpty(param.getOrder_id(), param.getRide_type(), param.getDriver_id(),
                param.getDriver_phone(), param.getDriver_name(), param.getCar_brand(), param.getCar_plate_number(), param.getCar_color())) {
            log.info("调用司机抢单接口参数问题2");
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        String cityId = param.getCityId();
        param.setCityId(null);
        try {
            OaSysDispatchLog dispatchLog = new OaSysDispatchLog();
            dispatchLog.setType(EDispatchType.grabOrdersBefore.getType());
            dispatchLog.setOrderId(param.getOrder_id());
            dispatchLog.setLogId(IDUtil.nextId());
            dispatchLog.setCityId(cityId);
            dispatchLog.setTimestamp(System.currentTimeMillis());
            producer.sendMsg(dispatchLog, EDispatchType.grabOrdersBefore.getDesc(), "LHY_EVENT");
//            iMqService.getDispatchLog(dispatchLog);
        } catch (Exception e) {
            log.error("记录订单调度日志!");
        }
        String carBrand = param.getCar_brand();
        String carBrandNew = carBrand.substring(0, carBrand.indexOf('·'));
        param.setCar_brand(carBrandNew);
        log.info("进入司机抢单接口");
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.STRIVE_CALL_BACK_API;
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        param.setApp_id(DiDiUrlConstant.didiAppId);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
//        JSONObject jsonObject = null;
//        try {
//            log.info("调用前======http调用滴滴接口，访问地址为：{" + url + "}访问参数为：{" + signParameter + "}");
//            String data = RetryUtil.retryRequestMethodUtil(signParameter, url, 3, 500L, 2.0);
//            log.info("调用后======http调用滴滴接口返回成功，访问地址为：{" + url + "}返回为：{" + data + "}");
//            jsonObject = JSONObject.parseObject(data);
//        } catch (Exception e) {
//            log.info("调用后======http调用滴滴接口 Exception，异常信息为" + e.getMessage());
//        }
//        if (CheckUtil.objIsEmpty(jsonObject) || CheckUtil.objIsEmpty(jsonObject.get(DiDiUrlConstant.ERRNO))) {
//            // 访问不到按照else走
//            log.info("调用滴滴司机抢单接口HTTP请求失败，返回值为" + jsonObject.toJSONString() + "准备释放司机运力");
//            // 对redis中的数据进行删除key操作
//            redisCleanOrderMsg(param.getOrder_id());
//            // 修改订单状态
////            iMqService.singleFailureStatus(param.getOrder_id());
//            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
//        }
//        Object errno = jsonObject.get(DiDiUrlConstant.ERRNO);
//        try {
//            OaSysDispatchLog dispatchLog = new OaSysDispatchLog();
//            dispatchLog.setType(EDispatchType.grabOrdersAfter.getType());
//            dispatchLog.setOrderId(param.getOrder_id());
//            dispatchLog.setLogId(IDUtil.nextId());
//            dispatchLog.setCityId(cityId);
//            if (CheckUtil.objIsNotEmpty(errno)) {
//                dispatchLog.setSyncResultCode(errno.toString());
//            }
//            dispatchLog.setTimestamp(System.currentTimeMillis());
//            producer.sendMsg(dispatchLog, EDispatchType.grabOrdersAfter.getDesc(),"LHY_EVENT");
////            iMqService.getDispatchLog(dispatchLog);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("记录订单调度日志!");
//        }
//
//        // 抢单成功
//        if (errno.equals(EDiDiErrorCode.success.getValue())) {
        // 进行一个异步回调，查看订单状态，防止滴滴司机抢单结果同步回调失败（5秒查一次，最长时限10秒）
        log.info("调用后======http调用滴滴接口成功，并且抢单成功，开始告诉司机接单");
        OrderDetailParam orderDetailParam = new OrderDetailParam();
        orderDetailParam.setOrder_id(param.getOrder_id());
        orderDetailParam.setOpen_oid(param.getOpen_oid());
        // 将MQ服务间调用更改为直发 --- hu
//            iMqService.getDidiSheet(orderDetailParam);
        producer.sendMsg(orderDetailParam, MqConstant.DIDI_GRAB_SHEET_TAG, null);
        return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
//        } else {
//            log.info("调用后======http调用滴滴接口成功，但是抢单失败，开始释放司机运力");
//            // 对redis中的数据进行删除key操作
//            redisCleanOrderMsg(param.getOrder_id());
        // 修改订单状态，统一订单被别人抢
//            iMqService.singleFailureStatus(param.getOrder_id());
//        }
//
//        return DiDiRv.wrapSuccess(EDiDiErrorCode.getStriveCallbackFail);


    }

    private void redisCleanOrderMsg(String order_id) {
        String orderNo = order_id;
        String key = RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo;
        String keyVeh = RedisPrefixConstant.ORDER_VEH_TEMPORARY_STORAGE + orderNo;
        redisCommon.remove(keyVeh);
        redisCommon.remove(key);
    }

    /**
     * 查询订单详情
     *
     * @param param 查询参数
     * @return
     */
    @Override
    public DiDiRv getOrderDetail(OrderDetailParam param) {
        log.error("(ORDER服务)调用查询订单详情失败，参数：{}", param.toString());
//        return DiDiRv.wrapError(EDiDiErrorCode.orderDetailFeignError);

        OrderDetailResults results = new OrderDetailResults();
//        String data = orderCorrelation(param, DiDiUrlConstant.ORDER_DETAIL_API);
//        if (CheckUtil.strIsEmpty(data)) {
//            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
//        }
//        JSONObject jsonObject = JSONObject.parseObject(data);
//        if (CheckUtil.objIsNotEmpty(jsonObject) && jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
//            JSONObject dataObject = jsonObject.getJSONObject("data");
        OaCOrderPersonal personal = getOaCOrderPersonalVersion(param);
        // 修改订单表
        UpdateWrapper<OaCOrderPersonal> updateWrapper = new UpdateWrapper<>();
        results.setStatus("4");
        getOrderStatus(personal, results.getStatus());
//            if (StringUtils.isNotBlank(dataObject.getString("passenger_phone"))) {
        results.setPassenger_phone("123456");
//                updateWrapper.set(OaCOrderPersonal.PASSENGER_PHONE, results.getPassenger_phone());
//            }
//            if (StringUtils.isNotBlank(dataObject.getString("passenger_phone_suffix"))) {
        results.setPassenger_phone_suffix("123");
//                updateWrapper.set(OaCOrderPersonal.PASSENGER_PHONE_SUFFIX, results.getPassenger_phone_suffix());
//            }
        updateWrapper.set(OaCOrderPersonal.VERSION, personal.getVersion() + 1);
        updateWrapper.set(OaCOrderPersonal.UPDATE_TIME, new Date());
        updateWrapper.eq(OaCOrderPersonal.ORDER_NO, param.getOrder_id());
        updateWrapper.eq(OaCOrderPersonal.VERSION, personal.getVersion());
        try {
            int update = oaCOrderPersonalMapper.update(null, updateWrapper);
            if (update < 1) {
                throw DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
            }
        } catch (Exception e) {
            log.error(e.getMessage());
            throw DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
        }
        return DiDiRv.wrap(EDiDiErrorCode.success, results);
//        } else {
//            throw DiDiException.create(EDiDiErrorCode.serverError);
//        }


    }

    /**
     * 查询version
     *
     * @param param 查询参数
     * @return OaCOrderPersonal
     */
    private OaCOrderPersonal getOaCOrderPersonalVersion(OrderDetailParam param) {
        // 查询version
        QueryWrapper<OaCOrderPersonal> queryVersion = new QueryWrapper<>();
        queryVersion.select(OaCOrderPersonal.VERSION);
        queryVersion.eq(OaCOrderPersonal.ORDER_NO, param.getOrder_id());
        List<OaCOrderPersonal> oaCOrderPersonals = oaCOrderPersonalMapper.selectList(queryVersion);
        if (CheckUtil.collectionIsEmpty(oaCOrderPersonals)) {
            throw DiDiException.create(EDiDiErrorCode.orderPersonalSelectFail);
        }
        return oaCOrderPersonals.get(0);
    }

    /**
     * 处理订单
     *
     * @param param
     */
    public String orderCorrelation(OrderDetailParam param, String urlSuffix) {
        if (StringUtils.isBlank(param.getOrder_id())) {
            throw DiDiException.create(EDiDiErrorCode.parameterError);
        }
        String url = DiDiUrlConstant.didiUrl + urlSuffix;
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        // 请求滴滴
        return RequestMethodUtil.requestMethod(signParameter, url);
    }

    /**
     * 获取订单的状态
     *
     * @param personal
     * @param status
     * @return
     */
    public void getOrderStatus(OaCOrderPersonal personal, String status) {
        if (StringUtils.isNotBlank(status)) {
            EDiDiOrderStatus byDidiType = EDiDiOrderStatus.findByDidiType(Integer.valueOf(status));
            if (CheckUtil.objIsNotEmpty(personal)) {
                personal.setOrderStatus(byDidiType.getType());
                personal.setDidiOrderStatus(byDidiType.getDidiType());
            }
        }
    }

    /**
     * 查询订单状态
     *
     * @param orderDetailParam 查询参数
     * @return
     */
    @Override
    public DiDiRv getOrderStatus(OrderDetailParam orderDetailParam) {
        log.error("(ORDER服务)调用查询订单状态失败，参数：{}", orderDetailParam.toString());
        return DiDiRv.wrapError(EDiDiErrorCode.orderStatusFeignError);
    }

    /**
     * 司机抢单结果feign调用
     *
     * @param param 抢单结果同步参数
     */
    @Override
    public DiDiRv driverSingleSynchronousFeign(DriverSingleSynchronousParam param) {

        if (StringUtils.isBlank(param.getStrive_status()) || StringUtils.isBlank(param.getOrder_id())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        log.info("被滴滴调用======司机抢单结果同步被调用了");
        String securityKey = RedisPrefixConstant.DIDI_GRAB_SHEET_RESULT + param.getOrder_id();
        // 安全机制防止异步错误
        if (redisCommon.hashKey(securityKey)) {
            log.info("被滴滴调用======滴滴抢单结果回调被调用了，我来删除Redis的回调信息，并return");
            redisCommon.remove(securityKey);
            return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
        } else {
            // 通知mq得到结果
            log.info("被滴滴调用======滴滴抢单结果回调没有被调用，告诉大家我调用了，继续下面操作");
            redisCommon.set(securityKey, "true", 15);
        }

        try {
            QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
            queryWrapper.select(OaCOrderPersonal.CITY_ID);
            queryWrapper.eq(OaCOrderPersonal.ORDER_NO, param.getOrder_id());
            List<OaCOrderPersonal> oaCOrderPersonals = oaCOrderPersonalMapper.selectList(queryWrapper);
            OaCOrderPersonal orderPersonal = oaCOrderPersonals.get(0);
            OaSysDispatchLog dispatchLog = new OaSysDispatchLog();
            dispatchLog.setType(EDispatchType.orderSynchronize.getType());
            dispatchLog.setOrderId(param.getOrder_id());
            dispatchLog.setAsyncNoticeGrapResult(Integer.valueOf(param.getStrive_status()));
            dispatchLog.setLogId(IDUtil.nextId());
            dispatchLog.setTimestamp(System.currentTimeMillis());
            if (CheckUtil.objIsEmpty(orderPersonal)) {
                dispatchLog.setCityId(orderPersonal.getCityId());
            }
            producer.sendMsg(dispatchLog, EDispatchType.orderSynchronize.getDesc(), "LHY_EVENT");
//            iMqService.getDispatchLog(dispatchLog);
        } catch (Exception e) {
            log.error("记录订单调度日志!");
        }
        // 成功
        if (StringUtils.equals(param.getStrive_status(), "1")) {
            log.info("被滴滴调用======司机抢单结果同步，回调抢单成功");
            // 查询订单信息

            QueryWrapper<OaCOrderPersonal> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq(OaCOrderPersonal.ORDER_NO, param.getOrder_id());
            List<OaCOrderPersonal> oaCOrderPersonals = oaCOrderPersonalMapper.selectList(queryWrapper);
            OaCOrderPersonal oaCOrderPersonal = oaCOrderPersonals.get(0);
            Long driverId = oaCOrderPersonal.getDriverId();
            log.info("获取到的司机driverId为：{}，订单号为：{}", driverId, oaCOrderPersonal.getOrderNo());
            //获取司机订单暂存信息
            String str = redisCommon.getStr(String.format("%s%s", RedisPrefixConstant.ORDER_VEH_TEMPORARY_STORAGE, oaCOrderPersonal.getOrderNo()));
            log.info("获取到的司机strstrstrstrstrstr：{}", str);
            if (CheckUtil.strIsNotEmpty(str)) {
                log.info("准备开始给司机推送，判断是等待应答的订单才给推送！");
                // 判断是等待应答的订单才给推送
                if (StringUtils.equals(oaCOrderPersonal.getDidiOrderStatus().toString(), EDiDiOrderStatus.waitingResponse.getDidiType().toString())) {
                    log.info("是等待应答的订单！");
                    Date dateTime = new Date();
                    NettyDriverOrderInfo nettyDriverOrderInfo = JSON.parseObject(str, NettyDriverOrderInfo.class);
                    // 修改订单表数据
//                    oaCOrderPersonal.setPassengerPhone(param.getPassenger_phone());
//                    oaCOrderPersonal.setPassengerPhoneSuffix(param.getPassenger_phone_suffix());
                    oaCOrderPersonal.setOrderStatus(EDiDiOrderStatus.driverOrder.getType());
                    oaCOrderPersonal.setDidiOrderStatus(EDiDiOrderStatus.driverOrder.getDidiType());
                    oaCOrderPersonal.setGpsId(nettyDriverOrderInfo.getGpsId());
                    oaCOrderPersonal.setMeetPassengerTime(dateTime);
                    // 获取uploadId
//                    try {
//                        String savePath = oaCOrderPersonal.getOrderNo() + ".mp3";
//                        String uploadId = iAmapService.getUploadId(savePath);
//                        uploadId = uploadId.replaceAll("\"", "");
//                        oaCOrderPersonal.setUploadId(uploadId);
//                    } catch (Exception e) {
//                        log.info("获取uploadId失败，报错信息为{}", e.getMessage());
//                    }
//                    oaCOrderPersonal.setUserId();
                    int updateById = oaCOrderPersonalMapper.updateById(oaCOrderPersonal);
                    if (updateById < 1) {
                        log.error("修改订单信息失败，订单号为：{}，司机ID为：{}", oaCOrderPersonal.getOrderNo(), driverId);
                        throw DiDiException.create(EDiDiErrorCode.orderPersonalUpdateFail);
                    }

                    //获取gpsId
                    // 司机接单表添加数据
                    OaDOrder oaDOrder = new OaDOrder();
                    // 获取司机接单位置
                    String gpsStr = redisCommon.getStr(RedisPrefixConstant.GPS_VEH_KEY_PREFIX + driverId);
                    if (CheckUtil.strIsNotEmpty(gpsStr)) {
                        OaDVehicleGps oaDVehicleGps = JSON.parseObject(gpsStr, OaDVehicleGps.class);
                        String lng = oaDVehicleGps.getLng();
                        String lat = oaDVehicleGps.getLat();

                        // 同步滴滴司机位置
                        LocationSyncParam locationSyncParam = new LocationSyncParam();
                        locationSyncParam.setOpen_oid(param.getOpen_oid());
                        locationSyncParam.setOrder_id(param.getOrder_id());
                        locationSyncParam.setDriver_id(oaDVehicleGps.getDriverId().toString());
                        Date date = new Date();
                        long timestampms = date.getTime();
                        locationSyncParam.setTimestampms(timestampms);
                        locationSyncParam.setLat(new BigDecimal(lat));
                        locationSyncParam.setLng(new BigDecimal(lng));
//                        getLocationSync(locationSyncParam);

                        oaDOrder.setPickPassengersFlng(lng);
                        oaDOrder.setPickPassengersFlat(lat);
                        log.info("司机开始接单======开始地址的逆地理编码，我准备开始获取了");
                        String regeo = iAmapService.getRegeo(lng + "," + lat);
                        log.info("司机开始接单======我调用成功了，数据为：" + regeo);
                        regeo = regeo.replaceAll("\"", "");
                        if (CheckUtil.strIsEmpty(regeo)) {
                            log.info("调用地址逆编码为空！！！继续接单");
                        } else {
                            log.info("调用地址逆编码为不为空！！！继续接单");
                            oaDOrder.setPickPassengersAddress(regeo);
                        }
                    }
                    oaDOrder.setOrderNo(param.getOrder_id());
                    oaDOrder.setDriverId(Long.valueOf(driverId));
                    // 司机接单时间
                    oaDOrder.setStriveTime(dateTime);
                    oaDOrder.setUserOrderId(oaCOrderPersonal.getPersonalId() + "");
                    oaDOrder.setUpdateTime(dateTime);
                    oaDOrder.setOrderType(oaCOrderPersonal.getOrderType());
                    oaDOrder.setUpdateUser(1L);
                    oaDOrder.setCreateTime(dateTime);
                    oaDOrder.setCreateUser(1L);
                    oaDOrder.setPassengerPhone(oaCOrderPersonal.getPassengerPhone());
                    oaDOrder.setFlat(oaCOrderPersonal.getStartLat());
                    oaDOrder.setFlng(oaCOrderPersonal.getStartLng());
                    oaDOrder.setTlat(oaCOrderPersonal.getEndLat());
                    oaDOrder.setTlng(oaCOrderPersonal.getEndLng());
                    oaDOrder.setOrderStatus(EDiDiOrderStatus.driverOrder.getType());
                    oaDOrder.setVehicleId(Long.valueOf(oaCOrderPersonal.getVehicleId()));
                    log.info("被滴滴调用======我要开始添加司机接单表的信息，准备完毕");
                    oaDOrderService.save(oaDOrder);
//                    Boolean aBoolean = iMqService.addDriverOrderInfo(oaDOrder);
//                    if (!aBoolean) {
//                        throw DiDiException.create(EDiDiErrorCode.driverOrderCreateFail);
//                    }
                    log.info("被滴滴调用======成功添加司机接单表的信息");
                    redisCommon.set(RedisPrefixConstant.ORDER_OA_D_ORDER + oaCOrderPersonal.getOrderNo(), JSON.toJSONString(oaCOrderPersonal));
                    nettyDriverOrderInfo.setPhone(param.getPassenger_phone());
                    nettyDriverOrderInfo.setTailNumber(param.getPassenger_phone_suffix());
                    //获取token
                    HashMap tokenUserKey = redisCommon.getHashMap("tokenUserKey");
                    if (CheckUtil.mapIsEmpty(tokenUserKey)) {
                        log.info("无法获取到token列表!");
                    } else {
                        // 获取司机最新的token
                        String driverTokenKey = driverId + ":Driver";
                        Object redisDriverToken = tokenUserKey.get(driverTokenKey);
                        if (CheckUtil.objIsEmpty(redisDriverToken)) {
                            log.info("未获取用户token,无法继续进行!,redis_key: {},redis_token: {}", driverTokenKey, redisDriverToken);
                        } else {
                            nettyDriverOrderInfo.setDriverToken(redisDriverToken.toString());
                        }
                    }
                    // redis添加数据等待司机接单
                    redisCommon.set(String.format("%s%s", RedisPrefixConstant.ORDER_VEH, driverId), JSON.toJSONString(nettyDriverOrderInfo));
                    // 给司机发送短信进行强通知
                    OaDUser user = oaDUserMapper.selectById(driverId);
                    String driverPhone = user.getDriverPhone();
                    // QCloudSMSUtils.sendMessage(driverPhone, QCloudSmsConstant.DRIVER_ORDER_MSG, (ArrayList<String>) null);
                    AliCloudSMSUtils.sendMessage(driverPhone, AliCloudSmsConstant.DRIVER_ORDER_MSG, null);
                    // 给司机推送消息进行强通知
                    driverPushMessage(driverPhone);

                    // 存入预估轨迹
                    String estimateKey = RedisPrefixConstant.DIDI_ESTIMATE + oaCOrderPersonal.getEstimateId();
                    HashMap<String, Object> hashMap = redisCommon.getHashMap(estimateKey);
                    String polyStr = hashMap.get(EGould.gouldPolyline.getValue()).toString();
                    if (CheckUtil.strIsEmpty(polyStr)) {
                        log.error("创建订单时，Redis预估轨迹获取失败！参数为{" + polyStr + "}");
                    }
                    String[] splitPolyList = polyStr.split(";");
                    if (splitPolyList.length < 1) {
                        log.error("创建订单时，Redis预估轨迹格式错误！参数为{" + splitPolyList.toString() + "}");
                    }
                    List<OaSysTrajectory> trajectoryList = new ArrayList<>();
                    for (String splitPoly : splitPolyList) {
                        String[] splitList = splitPoly.split(",");
                        if (splitList.length < 2) {
                            log.error("创建订单时，Redis预估轨迹经纬度不是成对的！参数为{" + splitList.toString() + "}");
                        }
                        OaSysTrajectory oaSysTrajectory = new OaSysTrajectory();
                        long id = IDUtil.nextId();
                        oaSysTrajectory.setTrajectoryId(id);
                        oaSysTrajectory.setOrderNo(param.getOrder_id());
                        oaSysTrajectory.setLng(splitList[0]);
                        oaSysTrajectory.setLat(splitList[1]);
                        oaSysTrajectory.setCreateTime(dateTime);
                        oaSysTrajectory.setCreateUser(oaCOrderPersonal.getDidiUserId());
                        trajectoryList.add(oaSysTrajectory);
                    }

//                    iOaSysTrajectoryService.saveBatch(trajectoryList);

                }
            } else {
                log.error("获取司机订单暂存信息为空：{}，订单号为：{}", str, param.getOrder_id());
            }
        } else {
            // 失败
            log.info("被滴滴调用======司机抢单结果同步，回调抢单失败,尝试取消订单");
            redisCleanOrderMsg(param.getOrder_id());
            // 修改订单状态，统一订单被别人抢
//            iMqService.singleFailureStatus(param.getOrder_id());
        }
        return DiDiRv.wrapSuccess(EDiDiErrorCode.success);

    }

    public void driverPushMessage(String driverPhone) {
        List<String> aliasList = new ArrayList<>();
        aliasList.add(driverPhone);
        JSONObject jsonObject = new JSONObject();
        JSONObject result = new JSONObject();
        result.put("title", MessageConstant.ORDER_INFORM);
        jsonObject.put("expand", JSON.toJSONString(result));
        PushInfoEntity pushInfoEntity = new PushInfoEntity();
        pushInfoEntity.setPushCode(EPushCode.driverOrderInform.getValue());
        pushInfoEntity.setPhones(aliasList);
        pushInfoEntity.setExtras(jsonObject);
        pushInfoEntity.setContent(MessageConstant.RECEIVED_ORDER_INFORM);
        pushInfoEntity.setTag("lhy");
        pushInfoEntity.setClientId(EJPushConfigKey.driver.getValue());
        pushInfoEntity.setJudgeCms("DRIVER");
        pushInfoEntity.setTitle(MessageConstant.ORDER_INFORM);
        pushInfoEntity.setPushLink("");
        //TODO
        log.info("给司机推送消息--------------------");
        log.info("给司机推送消息--------------------");
        log.info("给司机推送消息--------------------");
        log.info("给司机推送消息--------------------");
        log.info("给司机推送消息--------------------");
        log.info("给司机推送消息--------------------");
        log.info("给司机推送消息--------------------");
        iAmapService.pushMessage(pushInfoEntity);
    }


    /**
     * 调用支付详情
     *
     * @param closeOrderParam 参数
     * @return PayInfo
     */
    @Override
    public PayInfo getPayInfo(CloseOrderParam closeOrderParam) {
        log.error("(ORDER服务)调用司机抢单结果同步失败，参数：{}", closeOrderParam.toString());
        return null;
    }

}
